Variable Explorer

A quick notebook to show how to explorer different varaibles inside a netCDF file

Steps

  • Import the necessary libraries

  • Import the data file

  • Create the plotting function

  • Create the “tool”

import xarray as xr #Used to handle netCDF fiels
import hvplot.xarray # Add interactive plotting through holoviz ecosystem to xarray

# Panel is holoviz tool for "dashboarding" here we use the "interact" function which builds stuff intelligently
from panel.interact import interact
filename = '~/Documents/Data/PFTmap_14Ma_Straume_2x2.nc'
ds = xr.open_dataset(filename, decode_times=False) # decode_times is set to false because simulation times causes some funky behaviour
ds
<xarray.Dataset>
Dimensions:       (lat: 360, lon: 720, time_counter: 1, veget: 13)
Coordinates:
  * lon           (lon) float64 -179.8 -179.2 -178.8 ... 178.8 179.2 179.8
  * lat           (lat) float64 89.75 89.25 88.75 88.25 ... -88.75 -89.25 -89.75
  * veget         (veget) int32 1 2 3 4 5 6 7 8 9 10 11 12 13
  * time_counter  (time_counter) float64 1.0
Data variables:
    maxvegetfrac  (time_counter, veget, lat, lon) float32 ...
Attributes:
    title:    Straume_40Ma_pft
    history:  Tue Jan 26 11:20:27 2021

This is the function that actually does the plotting. A lot of “cleverness” resides inside the holoviz and xarray libraries. Here we are just telling the library to plot a given variable using image (a map) and setting the colormap.

xarray recoginizes (don’t know how) the longitude / latitude coordinates and looks at all the other coordinates availible. It sees the extra two dimensions and builds automatically the tools on the right hand side to vary these.

def plot(variable):
    return ds[variable].hvplot.image().opts(cmap='viridis')

Interact is a neat little tool, it takes a function and its arguments and builds the dashboard for us. Here we want to use the plotting function and provide be able to changfe the variable (which is accesible via ds.data_vars)

interact(plot, variable = list(ds.data_vars))